﻿using TinyCms.Infrastructure.Ioc;

namespace TinyCms.Core.Repositories
{
    /// <summary>
    /// 仓储上下文管理类
    /// 注意此类不可以被继承
    /// </summary>
    public sealed class RepositoryContextManager : DisposableObject, IUnitOfWork
    {
        #region Private Fields
        private readonly IRepositoryContext _context;
        #endregion

        #region Ctor

        /// <summary>
        /// 仓储上下文构造器
        /// 传入仓储上下文在spring.xml中定义的对象名
        /// </summary>
        /// <param name="type"></param>
        public RepositoryContextManager(string type)
        {
            _context = ServiceLocator.Instance.GetObject<IRepositoryContext>(type);
        }
        #endregion

        #region Protected Methods
        /// <summary>
        /// Disposes the object.
        /// </summary>
        /// <param name="disposing">A <see cref="System.Boolean"/> value which indicates whether
        /// the object should be disposed explicitly.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        #endregion

        #region Public Properties
        /// <summary>
        /// Gets the instance of the managed repository context.
        /// </summary>
        public IRepositoryContext Context
        {
            get { return _context; }
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// 获取对应具体领域对象的仓储模型
        /// </summary>
        /// <typeparam name="T">仓储对象类型</typeparam>
        /// <param name="entityname">默认为<see cref="T"/>的类型名称
        /// 请对应好在Spring.xml中的配置</param>
        /// <returns></returns>
        public IRepository<T> GetRepository<T>(string entityname=null)
            where T :EntityBase
        {
            if (string.IsNullOrEmpty(entityname))
                entityname = typeof (T).Name;
            return ServiceLocator.Instance.GetObject<IRepository<T>>(entityname);
        }
        #endregion

        #region IUnitOfWork Members
        /// <summary>
        /// Gets a <see cref="System.Boolean"/> value which indicates whether the UnitOfWork
        /// was committed.
        /// </summary>
        public bool Committed
        {
            get { return _context.Committed; }
        }
        /// <summary>
        /// Commits the UnitOfWork.
        /// </summary>
        public void Commit()
        {
            _context.Commit();
        }
        /// <summary>
        /// Rolls-back the UnitOfWork.
        /// </summary>
        public void Rollback()
        {
            _context.Rollback();
        }

        #endregion
    }
}
